package com.gyj.zookeeper.ZookeeperApi;

import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;
import java.util.concurrent.CountDownLatch;

/**
 * Created by Gao on 2018/10/23.
 * 动物园管理员类提供的getData方法来获取附加在指定Z序节点中的数据及其状态。 的getData方法的签名如下：
 * getData(String path, Watcher watcher, Stat stat)
 * path  - Znode路径。
 * watcher  - 监视器类型的回调函数。当指定的znode的数据改变时，ZooKeeper集合将通过监视器回调进行通知。这是一次性通知。
 * stat - 返回znode的元数据。
 */
public class ZKGetData {
    private static ZooKeeper zk;
    private static ZKConnection conn;

    public static Stat znode_exists(String path) throws
            KeeperException, InterruptedException {
        return zk.exists(path, true);
    }

    public static void main(String[] args) throws InterruptedException, KeeperException {
        String path = "/MyFirstZnode";
        final CountDownLatch connectedSignal = new CountDownLatch(1);
        try {
            conn = new ZKConnection();
            zk = conn.connect("localhost");
            Stat stat = znode_exists(path);
            if (stat != null) {
                byte[] b = zk.getData(path, new Watcher() {
                    public void process(WatchedEvent we) {
                        System.out.println("进入到process:");
                        if (we.getType() == Event.EventType.None) {
                            switch (we.getState()) {
                                case Expired:
                                    connectedSignal.countDown();
                                    break;
                            }
                        } else {
                            String path = "/MyFirstZnode";
                            try {
                                byte[] bn = zk.getData(path, false, null);
                                String data = new String(bn, "UTF-8");
                                System.out.println("取变化后的数据" + data);
                                //监测数据变化，当第一次拿到数据后，一直在监测，当通过客户端再次改变数据时候，能立即监测到数据变化
                                //并拿到新的数据，然后执行countDown()切断监测
                                connectedSignal.countDown();
                            } catch (Exception ex) {
                                System.out.println(ex.getMessage());
                            }
                        }
                    }
                }, null);
                String data = new String(b, "UTF-8");
                System.out.println("取的这里的数据：" + data);
                connectedSignal.await();
            } else {
                System.out.println("Node does not exists");
            }
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }
}
